<template>

  <div class="home-page" ref="homePage">
    <el-container>
      <!-- 顶栏 -->
  
      <el-header height="60px">
        <div class="headerDiv">
          <!-- <span>菜单</span> -->
          <h2 @click="drawer = true">声学：折线图</h2>
          <h2 @click="saveQrCode">下载</h2>
        </div>
      </el-header>

      <el-row>
     <el-button class="ImportButton" type="button" name="seach" @click="FuncCSVInportTwo">
            DrawTxt Import
      </el-button>
      <el-button class="ImportButton" type="button" name="seach" @click="FuncCSVInport">
            CSV Import
      </el-button>
      </el-row>

<el-drawer
  title="功能选择"
  :visible.sync="drawer"
  :direction="direction"
  :before-close="handleClose">
  <el-row class="tac">
  <el-col :span="24">
    <el-menu
      default-active="2"
      class="el-menu-vertical-demo"
      @open="handleOpen"
      @close="handleClose">
      <el-submenu index="1">
        <template slot="title">
          <i class="el-icon-location"></i>
          <span>声学</span>
        </template>
        <el-menu-item-group>
          <el-menu-item index="1-1" @click="clickMenu('1-1')">折线</el-menu-item>
          <el-menu-item index="1-2" @click="clickMenu('1-2')">cpk</el-menu-item>
        </el-menu-item-group>
      </el-submenu>

      <el-submenu index="2">
        <template slot="title">
          <i class="el-icon-location"></i>
          <span>光学</span>
        </template>
        <el-menu-item-group>
          <el-menu-item index="2-1" @click="clickMenu('2-1')">箱图</el-menu-item>
        </el-menu-item-group>
      </el-submenu>

    </el-menu>
  </el-col>
</el-row>

</el-drawer>
      <!-- 嵌套容器 -->
      <el-container>
        <!-- 侧边导航菜单 -->
        <!-- <el-aside width="150px"></el-aside> -->
        <!-- 内容 -->
        <el-main>
          <!-- 第一列栅格布局 -->
          <el-row>

            <el-col :span="24" class="col2">
               <el-table :data="allItem" ref="multipleTable" 
                v-el-table-infinite-scroll="load" border stripe    @selection-change="handleCurrentChange"
                height="300px">
                <el-table-column
                  type="index"
                  label="序号"
                  width="60"
                ></el-table-column>
                <el-table-column el-main prop="ItemName" label="Item Name"></el-table-column>
              </el-table>             
            </el-col>
            
          </el-row>
          <!-- 第二列布局 -->
          <div ref="qrCodeDiv">
            <el-row   v-for="(item, i) in allItem" v-bind:key="i" >
            <el-col :span="6">
              <el-row class="cpk-bg"  >
                <el-blank :span="6"><div class="grid-content bg-purple-dark"></div></el-blank>
              </el-row>
              <el-row class="cpk-bg" >
                <el-cpk :span="6"><div class="grid-content bg-purple-dark"> Limitup: {{limitup[i]}}</div></el-cpk>
              </el-row>
              <el-row class="cpk-bg" >
                <el-cpk :span="6"><div class="grid-content bg-purple-dark">LimitLow: {{limitlow[i]}}</div></el-cpk>
              </el-row>
              <el-row class="cpk-bg" >
                <el-cpk :span="6"><div class="grid-content bg-purple-dark">Data Count: {{count[i]}}</div></el-cpk>
              </el-row>
              <el-row class="cpk-bg"  >
                <el-cpk :span="6"><div class="grid-content bg-purple-dark">NA Count:{{failcount[i]}}</div></el-cpk>
              </el-row>
              <el-row class="cpk-bg"  >
                <el-cpk :span="6"><div class="grid-content bg-purple-dark">Failure Count:{{failurecount[i]}}</div></el-cpk>
              </el-row>
              <el-row class="cpk-bg"  >
                <el-cpk :span="6"><div class="grid-content bg-purple-dark">Max:{{max[i]}}</div></el-cpk>
              </el-row>
              <el-row class="cpk-bg"  >
                <el-cpk :span="6"><div class="grid-content bg-purple-dark">Min:{{min[i]}}</div></el-cpk>
              </el-row>
              <el-row class="cpk-bg"  >
                <el-cpk :span="6"><div class="grid-content bg-purple-dark">Mean:{{mean[i]}}</div></el-cpk>
              </el-row>
              <el-row class="cpk-bg"  >
                <el-cpk :span="6"><div class="grid-content bg-purple-dark">Std:{{std[i]}}</div></el-cpk>
              </el-row>
              <el-row class="cpk-bg"  >
                <el-cpk :span="6"><div class="grid-content bg-purple-dark">Cpu:{{cpu[i]}}</div></el-cpk>
              </el-row>
              <el-row class="cpk-bg"  >
                <el-cpk :span="6"><div class="grid-content bg-purple-dark">Cpl:{{cpl[i]}}</div></el-cpk>
              </el-row>
              <el-row class="cpk-bg"  >
                <el-cpk :span="6"><div class="grid-content bg-purple-dark">Cpk:{{cpk[i]}}</div></el-cpk>
              </el-row>



              <div class="grid-content bg-purple"></div>
            </el-col>
            <el-col :span="18" class="col3">

              <div class="titlestyle">{{title[i]}}</div>
               <div :id="i+'myChart'" :style="{ height: '350px' }"></div>

            </el-col>
            <div class="bline"></div>
          </el-row>
          </div>
          

        </el-main>
      </el-container>
      <!-- 底栏 -->
              <input
                type="file"
                id="files"
                ref="refFile"
                v-on:change="importCsv"
                style="opacity: 0"
              />
               <input
                type="file"
                id="refs2"
                ref="refFile2"
                v-on:change="importGrr"
                style="opacity: 0"
              />
      <el-footer height="30px">&copy;HWTE</el-footer>
    </el-container>
  </div>
</template>
<script >
import Papa from "papaparse";
import elTableInfiniteScroll from 'el-table-infinite-scroll'
import * as echarts from 'echarts';
import ecStat from 'echarts-stat';
import html2canvas from "html2canvas";
// echarts.registerTransform(transform.histogram);


export default {
  name: "HelloWorld",
  directives: {
    'el-table-infinite-scroll': elTableInfiniteScroll
  },
  data() {
    return {
      msg: "Welcome to Your Vue.js App",
      drawer: false,
      direction: 'ltr',
      clientHeight:'',
      allData:[],
      allBeginData:[],
      allItem:[],
      chatData:[],
      endLindata:[],
      multipleSelection: [],
      currentRow: null,
      title: [],
      itemList: [],
      limitArr:[],

      limitup:[],
      limitlow:[],
      count:[],
      failcount:[],
      failurecount:[],
      max:[],
      min:[],
      mean:[],
      std:[],
      cpu:[],
      cpl:[],
      cpk:[],
      cpkData:[],

    };
  },
  mounted() {
// 获取浏览器可视区域高度
      this.clientHeight =   `${document.documentElement.clientHeight}`          //document.body.clientWidth;
      //console.log(self.clientHeight);
      window.onresize = function temp() {
        this.clientHeight = `${document.documentElement.clientHeight}`;
      };
  },
  watch: {
      // 如果 `clientHeight` 发生改变，这个函数就会运行
      clientHeight: function () {
        this.changeFixed(this.clientHeight)
      }
  },
  methods: {

    saveQrCode () {
      html2canvas(this.$refs.qrCodeDiv).then(canvas => {
        const link = document.createElement('a')
        link.href = canvas.toDataURL()
        link.setAttribute('download', "666" + '.png')
        link.style.display = 'none'
        document.body.appendChild(link)
        link.click()
      })
    },
    handleOpen(key, keyPath) {
        console.log(key, keyPath);
      },


    clickMenu(value){
      if(value=="1-1"){
        this.$router.push({path:'/',query:{}});
      }
      if(value=="1-2"){
        this.$router.push({path:'/VidioCpk',query:{}});
      }
      if(value=="2-1"){
        this.$router.push({path:'/BoxLink',query:{}});
      }
         
      console.log(value)
    },
    changeFixed(clientHeight){                        //动态修改样式
        console.log(clientHeight);
        this.$refs.homePage.style.height = clientHeight+'px';

      },

      load(){},
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.SelectFinish();
    },
    //单选
    handleCurrentChange(val) {
            //  alert(111)
        console.log("12345678")
        console.log(val)
        // this.title = val.ItemName;
        console.log(val.ItemName)
        this.currentRow = val;
        this.SelectFinish();

    },
    importGrr() {
      let selectedFile = null;
      selectedFile = this.$refs.refFile2.files[0];
      console.log(selectedFile)

      if (selectedFile === undefined) {

        return;
      }
      var reader = new FileReader();
      reader.readAsDataURL(selectedFile);
      reader.onload = (evt) => {
        // 检查编码
        Papa.parse(selectedFile, {
          encoding: "ANSI",
          complete: (res) => {
            // UTF8 \r\n与\n混用时有可能会出问题
            let data = res.data;

            if (data[data.length - 1] == "") {
              //去除最后的空行
              data.pop();
            }
            // this.allData = data;
            var KeyArr=[];
            console.log('333333333333');
            console.log(data);

            for(var i=0;i<data.length;i++){
              var str=data[i];
              var datal = {};
              datal["ItemName"] = str;
              this.title.push(str["0"]);;
              console.log(str);

              this.allItem.push(datal);
        
            }

            this.currentRow = this.allItem;
            this.SelectFinish();

          },
        });
      };
    },
    importCsv() {
      console.log('++++++++')
      let selectedFile = null;
      selectedFile = this.$refs.refFile.files[0];
      if (selectedFile === undefined) {
        return;
      }
      var reader = new FileReader();
      reader.readAsDataURL(selectedFile);
      reader.onload = (evt) => {
        // 检查编码
        // let encoding = this.checkEncoding(evt.target.result);
        // 将csv转换成二维数组
        Papa.parse(selectedFile, {
          encoding: "ANSI",
          complete: (res) => {
            // UTF8 \r\n与\n混用时有可能会出问题
            let data = res.data;
            if (data[data.length - 1] == "") {
              //去除最后的空行
              data.pop();
            }
            this.allData = data;
            this.allBeginData = data;
            this.VidioBrokeline();
          },
        });
      };
    },
    VidioBrokeline() {
      var datas = [];
      let first = this.allData[1];
      var headers = first;
      for (var i = 4; i < 6; i++) {
        var datal = {};
        var temp = this.allData[i];
        for (var j = 0; j < temp.length; j++) {
          datal[headers[j]] = temp[j];
        }
        if (datal.Site != "") {
          this.limitArr.push(datal);
        }
      }

      for (var i = 7; i < this.allData.length; i++) {
        var datal = {};
        var temp = this.allData[i];
        for (var j = 0; j < temp.length; j++) {
          datal[headers[j]] = temp[j];
        }
        if (datal.Site != "") {
          datas.push(datal);
        }
      }
      console.log(datas);  // data就是文件里面的数据
      this.allData = datas;
      this.SelectFinish();
    },
    LineDetailData(obj, str) {
      var listMap = obj;
      var datas = {};
      var allkey = [];
      var allValue = [];
      Object.keys(listMap).forEach(function (key) {
        var csvarry = key.split("@");

        if (csvarry[0] == str) {
          var datal = {};
          datas[csvarry[1]] = listMap[key];
          allkey.push(csvarry[1]);
          allValue.push(listMap[key]);
        }
      });
      this.chatData = datas;
      return datas;
    },

    SelectFinish() {


      if(this.currentRow!=null){
     for (var j = 0; j < this.currentRow.length; j++) {
          // var x=[];
          var item=this.currentRow[j];
        console.log(item)
  
           
        var valueDataArr = [];
        var limit = [];
        for (var i = 0; i < this.allData.length; i++) {
          // var x=[];
          var listV=this.allData[i];
          var num= listV[item.ItemName];
          // x.push(num);
          // x.push(5);
          valueDataArr.push(num);
        }
          this.drawLine( valueDataArr,j,item.ItemName);

          this.mathCPK(valueDataArr,item.ItemName);
     }

        console.log(valueDataArr)


        // for (var i = 0; i < 2; i++) {
        //   this.drawLine( valueDataArr,i);
        
        //   this.mathCPK(valueDataArr);
        // }


      }

    },
    mathCPK(valueDataArr,ItemName){
      var Item = ItemName;
       console.log("89898989");

      console.log(Item);
      var limitlow = this.limitArr[1][Item];
      // console.log("limitlow",limitlow);
      var limitup = this.limitArr[0][Item];
      // console.log("limitup",limitup);
      
      var count = valueDataArr.length;
      console.log("count",count);
      var failcount = 0;
      var failurecount = 0;
      for (var i = 0;i < valueDataArr.length;i++){
        // let isExit = valueDataArr.findIndex(item => item === "NA")
        // console.log(isExit)
        if (valueDataArr[i] == "NA") {//存在
          console.log("cunzai NA");
          failcount  = failcount +1;
        }
        if (valueDataArr[i] < limitlow){
          console.log("failure");
          failurecount = failurecount +1;
        }
        if (valueDataArr[i] > limitup){
          console.log("failure");
          failurecount = failurecount +1;
        }
      }
      var max = Math.max.apply(null,valueDataArr);
      var min = Math.min.apply(null,valueDataArr);
      // console.log("max:",max," min:",min);
      // var mean = Math.mean(valueDataArr);
      // var std = Math.std(valueDataArr);
      
      
      var sum = 0;
      for(var i = 0;i < valueDataArr.length;i ++){
        var temp = parseFloat(valueDataArr[i]);
        sum = sum + temp;
        // console.log("sum",sum);
        // console.log("aaa",valueDataArr[i]);
      }
      var avg = sum/count;
      avg = Number(avg).toFixed(4);
      console.log("avg",avg);
      var sq = 0;
      for(var i =0;i<valueDataArr.length;i++){
        sq = (valueDataArr[i]-avg) * (valueDataArr[i]-avg) + sq;
        // console.log("i:",i," valueDataArr[i]:",valueDataArr[i]," sq:",sq);
      }
      // console.log("sq",sq);
      var std = Math.sqrt(sq/(count-1));
      console.log("std",std);
      var cpu = (limitup - avg)/(3 * std);
      var cpl = (avg - limitlow)/(3 * std);
      var cpk = Math.min(cpu,cpl);


      this.limitup.push(limitup);
      this.limitlow.push(limitlow) ;
      this.count.push(count)  ;
      this.failcount.push(failcount)  ;
      this.failurecount.push(failurecount)  ;
      this.max.push(max)  ;
      this.min.push(min)  ;
      this.mean.push(Number(avg).toFixed(4))   ;
      this.std.push(Number(std).toFixed(4))  ;
      this.cpu.push(Number(cpu).toFixed(4)) ;
      this.cpl.push(Number(cpl).toFixed(4))  ;
      this.cpk.push(Number(cpk).toFixed(4))  ;

    },

    drawLine(allValue,index,item) {


      var chartManager;

      chartManager = this.$echarts.init(document.getElementById(index+'myChart'));

      // chartManager = this.$echarts.init(document.getElementById('0myChart'));
                //随着屏幕大小调节图表
          window.addEventListener("resize", () => {
            chartManager.resize();
        });
        

        console.log("000000000")
        var interval;


      var Item = item;
      console.log(Item);
      var limitlow = this.limitArr[1][Item];
      console.log("limitlow",limitlow);
      var limitup = this.limitArr[0][Item];
      console.log("limitup",limitup);

      var max;
      var min;
      var mid_need;
      var x_up_border;
      var x_low_border; 

      max = Math.max.apply(null, allValue);
      min = Math.min.apply(null, allValue);

      if (limitup != 'NA' && limitlow != 'NA'){
          console.log("------------------UPLOW-----------------")
          mid_need = (Number(limitup) - Number(limitlow))/5;
          x_up_border = Number(limitup) + Number(mid_need);
          x_low_border = Number(limitlow) - Number(mid_need);
        }
      if (limitup == 'NA' && limitlow != 'NA'){
          console.log("------------------LOW-----------------")
          mid_need = (Number(max) - Number(limitlow))/5;
          x_up_border = Number(max) + Number(mid_need);
          x_low_border = Number(limitlow) - Number(mid_need);
        }
      if (limitup != 'NA' && limitlow == 'NA'){
          console.log("------------------UP-----------------")
          mid_need = (Number(limitup) - Number(min))/5;
          x_up_border = Number(limitup) + Number(mid_need);
          x_low_border = Number(min) - Number(mid_need);
        }
      if (limitup == 'NA' && limitlow == 'NA'){
          console.log("------------------NO-----------------")
          mid_need = (Number(max) - Number(min))/5;
          x_up_border = Number(max) + Number(mid_need);
          x_low_border = Number(min) - Number(mid_need);
        }

      function numCount(up_i, low_i){
          var cc = 0;
          for (var i in allValue) {
            if (allValue[i] != 'NA'){
              if ((Number(allValue[i]) > Number(low_i)) && (Number(allValue[i]) < Number(up_i))){
                  cc = Number(cc) + 1;
              }
            }
          }
          return cc;
      }

      var z = 0;
      var data = [];
      var dd = 0;
      var bins_n = (Number(x_up_border) - Number(x_low_border))/75;

      while(dd < 75) {
        var x0 = Number(x_low_border) + Number(z)*bins_n;
        var x1 = Number(x_low_border) + (Number(z)+1)*bins_n;
        z = Number(z)+1
        dd = Number(dd) + 1

        var count = numCount(x1, x0);
        if(count == 0){
            data.push([x0, x1, '']);
        }else{
            data.push([x0, x1, count]);
        }
      }
      console.log(data);

    // 自定义渲染效果
    function renderItem(params, api) {
        // 这个根据自己的需求适当调节
        var yValue = api.value(2);
        var start = api.coord([api.value(0), yValue]);
        var size = api.size([api.value(1) - api.value(0), yValue]);
        var style = api.style();

        return {
            // 矩形及配置
            type: 'rect',
            shape: {
                x: start[0] + 1,
                y: start[1],
                width: size[0] - 2,
                height: size[1]
            },
            style: style
        };
    }

      // 绘制图表
      chartManager.setOption({

        grid: {
            top: 80,
            containLabel: true
        },

        toolbox: {
        feature: {
            // saveAsImage: {}
          }
        },


        xAxis: [{
            type: 'value',
            

        }],
        yAxis: [{
            type: 'value',
            axisLine:{       //y轴
               "show":false

           },
        }],
        
        series: [{
            name: 'height',
            type: 'custom',
            renderItem: renderItem,
            label: {
                show: true,
                position: 'insideTop'
            },
            encode: {
                // 表示将data中的data[0]和data[1]映射到x轴
                x: [0, 1],
                // 表示将data中的data[2]映射到y轴
                y: 2,
                // 表示将data中的data[2]映射到tooltip
                tooltip: 2,
                // 表示将data中的data[2]映射到label
                label: 2
            },
            data: data,


             markLine : {
                symbol:"none",
            
                           /*symbol:"none",               //去掉警戒线最后面的箭头
                           label:{
                               position:"end"   ,       //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
                            
                            
                           },*/
                           data : [{
                                
                               silent:false,             //鼠标悬停事件  true没有，false有
                               lineStyle:{               //警戒线的样式  ，虚实  颜色
                                   type:"solid",
                                   color:"#FA3934",
                               },
                                   label:{
                                   position:'end',
                                   formatter:"Low"
                               },
                               xAxis:limitlow         // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                              
                           },
                           {
                             
                               silent:false,             //鼠标悬停事件  true没有，false有
                               lineStyle:{               //警戒线的样式  ，虚实  颜色
                                   type:"solid",
                                   color:"#FA3934",
                                    
                               },
                               label:{
                                   position:'end',
                                   formatter:"Up",
                               },
                               xAxis:limitup           // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                         
                           }
                           ]
          },




        },]

      });


    },
    
    FuncCSVInport() {
      // 使用vue的ref参数直接操作input的点击事件触发 importCsv
      this.$refs.refFile.dispatchEvent(new MouseEvent("click"));
    },    
    FuncCSVInportTwo() {
      // 使用vue的ref参数直接操作input的点击事件触发 importCsv
      this.$refs.refFile2.dispatchEvent(new MouseEvent("click"));
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

.el-header {
  background-color: #409eff;
  color: white;
  display:flex;
  text-align: left;
	flex-direction: column;
	justify-content: space-between;
}

.el-main{
  padding: 0px;
}
.el-footer {
  background-color: #d1d9e7;
  color: black;
  text-align: center;
}
.el-aside {
  background-color: chartreuse;
}
.el-main {
  background-color: rgb(191, 209, 174);
}
.el-col {
  height: 300px;
}
/* .el-cpk {
  height: 30px;
} */
.el-blank {
  height: 200px;
}

.titlestyle{
   margin-top: 30px;
  /* margin-bottom: 20px; */
}
.col1 {
  background-color: rgb(36, 128, 0);
  height: 45%;
}
.col2 {
  background-color: tomato;
  height: 45%;
}

.col3 {
  background-color: rgb(255, 255, 255);
  height: 45%;
}
.bline{
    position: relative;
    float: left;
    width: 100%;
    background-color: rgb(218, 218, 218);
    height: 1px;
}
.cpk-bg {
    height: 30px ;
}
.ImportButton{
}
.headerDiv{
  display: flex;
  justify-content: space-between
}

</style>
